﻿using MvvmCross.Core.ViewModels;
using System.Linq;
using System.Threading.Tasks;

namespace Sidvall.UI.Views
{
	public class RegionViewCollection : System.Collections.ObjectModel.KeyedCollection<string, RegionView>
	{
		#region Public Members

		#region Add

		public void Add(object container, string regionName, IViewFactory viewFactory, MvxViewModelRequest request)
		{
			RegionView item;

			if (this.Contains(regionName))
				return;
			item = new RegionView()
			{
				Container = container,
				RegionName = regionName,
				ViewFactory = viewFactory,
				Request = request,
			};
			Add(item);
		}

		#endregion
		#region GetKeyForItem

		protected override string GetKeyForItem(RegionView item)
		{
			if (item == null)
				throw new System.ArgumentNullException("item");
			return item.RegionName;
		}

		#endregion

		#region ShowViewsAsync

		public async Task ShowViewsAsync(RegionCollection regions)
		{
			System.Collections.Generic.List<string> showedItems;
			Region region;

			if (regions == null)
				return;

			showedItems = new System.Collections.Generic.List<string>();
			var items = (from o in this
						 orderby o.RegionName
						 select o);
			foreach (var item in items)
			{
				region = await regions.ShowViewAsync(item);
				if (region != null)
					showedItems.Add(item.RegionName);
			}
			foreach (var item in showedItems)
				Remove(item);
		}

		#endregion

		#endregion
		#region Constructors

		public RegionViewCollection()
		{
		}

		#endregion
	}
}
